package com.guiwu.gteway.industryapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.guiwu.gteway.industryapp.Api.GuiwuApi;
import com.guiwu.gteway.industryapp.Api.GuiwuApiCallback;
import com.guiwu.gteway.industryapp.Regist.RegisterActivity;
import com.guiwu.gteway.industryapp.util.MyLog;
import com.guiwu.gteway.industryapp.util.PreferencesUtil;
import com.guiwu.gteway.industryapp.util.ProgressSimpleDialog;
import com.guiwu.gteway.industryapp.util.ToastUtil;
//import com.videogo.openapi.EZOpenSDK;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by 乔冠 on 2017/12/25. 登录界面
 */

public class LogActivity extends RootActivity{

    private static final String TAG = "UserLog";
    private TextView mUserName;
    private TextView mUserPsw;
    private Button mLogBt;
    private ProgressSimpleDialog logDialog;
    private Context mActivityContext;
    private boolean isLoadName = true;//是否保存用户名密码

    //自己申请的萤石云appKey
    public static String AppKey = "686686c29d3c40c4b8bb12bab6b32870";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivityContext = this;
        setContentView(R.layout.login_layout);

        mUserName = findViewById(R.id.tv_user);
        mUserPsw = findViewById(R.id.tv_psw);
        mLogBt = findViewById(R.id.bt_log);


        initView();
        mLogBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        Button bt = findViewById(R.id.bt_register);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(RegisterActivity.newIntent(LogActivity.this));
            }
        });

    }

    //获取用户绑定的萤石云信息
    private void getAppKey(String userId) {
        GuiwuApi.getUserAppKey(userId, new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG,"appKey返回的数据"+ response);
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                int errno = jsonObject.get("errno").getAsInt();
                if (errno == 0){
                    if (jsonObject.has("data")){
                        JsonArray jsonArray = jsonObject.getAsJsonArray("data");
                        JsonObject appkeyObject = jsonArray.get(0).getAsJsonObject();
                        AppKey = appkeyObject.get("appKey").getAsString();
                        MyLog.i(TAG,"appkey获取成功" + AppKey);
                    }else {
                        Toast.makeText(getApplicationContext(),getString(R.string.login_info),Toast.LENGTH_LONG).show();
                        MyLog.i(TAG,"该用户没有绑定摄像头！");
                    }
 //                   initSDK();
                    logDialog.closeProgressDialog();
                    Toast.makeText(getApplicationContext(), R.string.login_success,Toast.LENGTH_SHORT).show();
                    Intent intent = MainActivity.newIntent(mActivityContext);
                    startActivity(intent);
                }else {
                    MyLog.i(TAG,"appkey获取失败" + jsonObject.get("error").getAsString());
                    logDialog.closeProgressDialog();
                }

            }

            @Override
            public void onFailed(Exception e) {
                MyLog.i(TAG,"appkey获取失败" + e.getMessage());
                logDialog.closeProgressDialog();
            }
        });



    }

    //登录
    private void login(){

        String requestBody = addLogContent(mUserName.getText().toString(),mUserPsw.getText().toString());
        //登录
        if ( requestBody!= null){
            //打开进度框
            logDialog = new ProgressSimpleDialog(mActivityContext);
            logDialog.showPorgressDialog(getString(R.string.logining));

            GuiwuApi.userLogin(requestBody, new GuiwuApiCallback() {
                //回调结果
                @Override
                public void onSuccess(String response) {
                    MyLog.i(TAG,"用户登陆返回：" + response);
                    JsonObject resp = new JsonParser().parse(response).getAsJsonObject();
                    int errno = resp.get("errno").getAsInt();
                    if (errno == 0){
                        JsonArray data = resp.getAsJsonArray("data");
                        JsonObject userIdJson = data.get(0).getAsJsonObject();
                        int userId = userIdJson.get("userId").getAsInt();
                        //保存userId
                        PreferencesUtil.getInstance(getApplicationContext()).putInt("userId",userId);
                        getAppKey(String.valueOf(userId));

                        SDKInitializer.initialize(getApplicationContext());
                    }else if (errno == 1){
                        logDialog.closeProgressDialog();
                        String  errorMessage = resp.get("error").getAsString();
                        ToastUtil.showToast(getApplicationContext(),errorMessage);
                      //  Toast.makeText(getApplicationContext(), errorMessage,Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailed(Exception e) {
                    MyLog.e(TAG,e.getMessage());
                    //关闭进度框
                    logDialog.closeProgressDialog();
                    ToastUtil.showToast(getApplicationContext(),getString(R.string.login_failed));
                   // Toast.makeText(mActivityContext, R.string.login_failed,Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    /**
     * 组装登录请求
     * @param userName
     * @param psw
     * @return 返回组装后的jsonString 失败返回空
     */
    private String addLogContent(String userName,String psw){

        String phoneNum = "[1][358]\\d{9}";
        String EmailNum = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

        if (userName.equals("") || psw.equals("")){
            Toast.makeText(mActivityContext, R.string.fill_information,Toast.LENGTH_SHORT).show();
            return null;
        }

        if (isLoadName){
            PreferencesUtil.getInstance(getApplicationContext()).putString("userName",userName);
            PreferencesUtil.getInstance(getApplicationContext()).putString("password",psw);
        }

        try {
            JSONObject requestContent = new JSONObject();

            if (userName.matches(phoneNum)){//手机号
                requestContent.putOpt("mobile",userName);
            }else if (userName.matches(EmailNum)){//邮箱
                requestContent.putOpt("email",userName);
            }else {//用户名
                requestContent.putOpt("userName",userName);
            }

            requestContent.putOpt("password",psw);

            return requestContent.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            MyLog.e(TAG,e.getMessage());
            return null;
        }
    }

    //填入保存的用户名和密码
    private void initView(){
        String userName = PreferencesUtil.getInstance(getApplicationContext()).getString("userName","");
        String psw = PreferencesUtil.getInstance(getApplicationContext()).getString("password","");
        if (isLoadName){
            mUserName.setText(userName);
            mUserPsw.setText(psw);
        }

    }

    //萤石云的sdk初始化
//    private void initSDK() {
//        {
//            /**
//             * sdk日志开关，正式发布需要去掉
//             */
//            EZOpenSDK.showSDKLog(false);
//
//            /**
//             * 设置是否支持P2P取流,详见api
//             */
//            EZOpenSDK.enableP2P(true);
//
//            /**
//             * APP_KEY请替换成自己申请的
//             */
//            EZOpenSDK.initLib(getApplication(), AppKey, "");
//        }
//
//
//        //初始化百度地图sdk
//        SDKInitializer.initialize(getApplicationContext());
//    }




}
